package com.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import Model.User;

public class TCPServer {
	public static void main(String[] args) {
		try {
			//建立服务，监听制定端口
			ServerSocket serverSocket = new ServerSocket(8800);
			
			//accept为阻塞方法，它将不会继续执行，除非在监听端口上捕获一个tcp连接请求
			//若改成while方法，即可实现多线程编程，一个服务，多个请求
			Socket socket = serverSocket.accept();
			
			//建立输入流，并用对象输入流包装
			InputStream is = socket.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			User user = (User) ois.readObject();
			
			System.out.println("Server Message:Get User From Client, name = " + user.getName());
			
			//关闭输入流
			socket.shutdownInput();
			
			//输出反馈消息
			PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
			pw.write("server accept a user model, name = " + user.name);
			pw.flush();
			pw.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
